'''
Created on 19.09.2012

@author: doleynik
'''
import json
import webapp2

from webapp2_extras.i18n import gettext as _

from apnetmodels.apnetusers import APNETUser
from google.appengine.api import users
from apnetmodels.basicmodels import syndic, syndicForUser, immeuble

from wtforms.ext.appengine.db import model_form

from common import functions

from BaseHandler import BaseHandler

class Syndics(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(Syndics, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.fields = {
                       'type': _('Type'), 'name': _('Name'), 'adress': _('Address'), 'additional_adress': _('Additional address'),
                       'postalcode': _('Postal code'), 'ville': _('City'), 'phone': _('Phone number 1'), 'phone_2': _('Phone number 2'),
                       'fax': _('Fax'), 'email': _('Email'), 'wwwsite': _('Site'), 'capital': _('Capital'),
                       'siret': _('SIRET'), 'ape': _('APE'), 'carteprof_g': _('Prof card G'), 'carteprof_t': _('Prof card F'),
                       'caissegarant': _('Guarantee desk'), 'n_dadherent': _('# of adherent'), 'caisse_adress': _('Guarantee desk address'),
                       'tva_num': _('VAT'), 'code_fournisseur': _('Supplier code'), 'storing_years': _('Storing years'),
                       'note_title': _('Title note')
                       }
    
    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)
    
    def op_detail_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        syn = imm.syndic
        SyndicForm = model_form(syndic, exclude=['creator','lastchange_by'])
        form = SyndicForm(obj = syn)
        
        desc = []
        for field in form:
            desc.append([unicode(_(self.fields[field.name])), unicode(field.data)])
        
        ret = {}
        ret['aaData'] = desc
        self.response.out.write(json.dumps(ret))
    
    def op_detail(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        syn = imm.syndic
        is_i_admin = syn.syndic_users.filter('user =', self.au).get()
        show_edit = False
        if is_i_admin and self.au.is_syndic_admin:
            show_edit = True
            
        template_values = {
                           'title': _('Syndic details. %s' % syn.name),
                           'header': _('%s. Syndic details.' % syn.name),
                           'app_user': self.au,
                           'immeuble': imm,
                           'syndic': syn,
                           'show_edit': show_edit,
                           'lurl': users.create_logout_url('/'),
                           'section': 'syndic',
                           'leftmenu': 'syndic',
                           'fields': self.fields
                           }

        template = self.jinja2.get_template('templates/syndic_detail.html')
        self.response.out.write(template.render(template_values))
        
    def op_edit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        syn = imm.syndic
        
        ok_message = ''
        SyndicForm = model_form(syndic, exclude=['creator','lastchange_by'])
        
        if self.request.method == 'GET':
            form = SyndicForm(obj = syn)
            
        if self.request.method == 'POST':
            form = SyndicForm(self.request.POST)
            
            if form.validate():
                form.populate_obj(syn)
                syn.put()
                ok_message = _('Syndic was updated.')
        
        template_values = {
                           'form': form,
                           'ok_message': ok_message,
                           'fields': self.fields
                           }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
